package org.xs.web.http;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;
import org.apache.velocity.app.VelocityEngine;
import org.xs.web.http.provider.HTTPHeader;
import org.xs.web.util.Reflections;

 
 
public class XSRules {
	private static Logger logger = Logger.getLogger(XSRules.class);
	public static VelocityEngine velocityEngine;
	public static String Encode="UTF-8";
	public static String ctxPath;
	public static String applicationControllerName= "applicationController";
	public static String xsAjax = "xsAjax";
	public static String validateMsgHtml="";
	
	public static String[] defaultLayout = {"/application.html","/default.html"};
	public static String defaultAction = "index";
	
	private  final static String[] ingoresVelocityTemplate;
	private  final static String[] counotVisiable;

	static{
		ingoresVelocityTemplate = new String[]{
				"org.apache",
				"org.springframework",
				"org.hibernate"
		};	
		counotVisiable = new String[]{
			".vm"	
		};
	}
	public static String templateDot(){
		return ".html";
	}
	public static String mergeTemplateName(String tirmPath){
		String[] parts = tirmPath.split("/");
		if(parts.length < 2){
			return "/"+parts[0]+ templateDot();
		}else{
			return tirmPath + templateDot();
		}
	}
	
	
	public static boolean canVisiable(String path){
		for(String i : counotVisiable){
			if(path.endsWith(i)){
				return true;
			}
		}
		return false;
	}
	
	public static boolean isXSControoler(Class<?> clazz){
		for(;clazz != Object.class;clazz = clazz.getSuperclass()){
			if(clazz == ActionController.class){
				return true;
			}
		}
		return false;
	}
	
	public static InvokeContext invokeActoin(String contName,Object cont,String actName,boolean notfound){
		Method method = Reflections.getMethodAndWrap(actName, cont.getClass());
		if(method == null){
			logger.warn("controller "+ contName+ " dose not have this method "+actName);
			return new InvokeContext(cont != null,false,false,null);
		}
		if(method.getParameterTypes().length > 0){
			logger.warn("method "+actName+ " have one or more arguments");
		}
		
		try {
			Object res = method.invoke(cont);
			return new InvokeContext(true, true, true, res);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	public static boolean isCanRenderTemplateBean(Class<?> clazz){
		for(;clazz != Object.class;clazz = clazz.getSuperclass()){
			if(clazz == ActionController.class){
				return false;
			}
		}
		String clazz_name = clazz.getName();
		for(String ingore : ingoresVelocityTemplate){
			if(clazz_name.startsWith(ingore)){
				return false;
			}
		}
		return true;
	}
	
	public static HTTPHeader[] defaultHeaders(){
		return new HTTPHeader[]{HTTPHeader.create("Power-By", "XS")};
	}
	
	public static String getNotfoundMessage(){
		return "资源找不到";
	}
	
}
